package servlet;

import static database.Config.properties;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

 
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.Iterator;

/**
 * Class pour mettre des images dans la base des donnes, d'abord on 
 * mette l'image sur un repertoire physique de la machine, puis on le 
 * sauvegarde dans la base de donnes en format binaire.
 * 
 * On utilise des classes pour mettre le fichiers dans l'ordinateur, ces classes
 * on l'a telecharge du site apache. Ils sont les fournisseurs de cettes clasees.
 * @author mrhorus
 *
 */
 
public class FileUploadDemoServlet extends HttpServlet {
    private static final long serialVersionUID = -3208409086358916855L;
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String user = (String) request.getSession().getAttribute("id");
        System.out.println(user);
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
 
            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
 
                    if (!item.isFormField()) {
                        String fileName = item.getName();
 
                        String root = getServletContext().getRealPath("/");
                        File path = new File(root + "/uploads");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }
 
                        File uploadedFile = new File(path + "/" + fileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                        
                        //Save to database
                        
                        PrintWriter pw = response.getWriter();
                        String connectionURL = "jdbc:mysql://localhost:3306/Luna"; //Il faut dire explicitement quel bd on va utiliser
                        Connection con=null;
                        try{
                                Class.forName(properties.getProperty("driver")).newInstance();
                                con = DriverManager.getConnection(properties.getProperty("dbURL"), properties.getProperty("username"), properties.getProperty("password"));
                                PreparedStatement ps = con.prepareStatement("UPDATE User SET photo = ? where user='"+user+"'");
                                File file = new File(uploadedFile.getAbsolutePath());
                                FileInputStream fs = new FileInputStream(file);                
                                ps.setBinaryStream(1,fs,fs.available());
                                //ps.setString(1, user);
                                int i = ps.executeUpdate();
                                if(i!=0){
                                        pw.println("Image inserted successfully");
                                        
                                        
                                }else{
                                        pw.println("Problem in image insertion");
                                }
                        } catch (Exception e){
                        System.out.println(e);
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}